package com.cloudspace.jindun.activity.Woyao;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.cloudspace.jindun.R;
import com.cloudspace.jindun.activity.CustomTitleBaseActivity;
import com.cloudspace.jindun.network.url.YXHttpUrl;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.FileUtil;
import com.cloudspace.jindun.utils.ObjUtil;
import com.cloudspace.jindun.utils.ToastMaker;
import com.cloudspace.jindun.utils.BitmapUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

//情报上报
public class IntelligenceActivity extends CustomTitleBaseActivity {

    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.activity_edit)
    EditText mActivityEdit;
    @Bind(R.id.activity_particulars_edit)
    EditText mActivityParticularsEdit;
    @Bind(R.id.iv01)
    ImageView mIv01;
    @Bind(R.id.iv02)
    ImageView mIv02;
    @Bind(R.id.iv03)
    ImageView mIv03;
    @Bind(R.id.activity_cBox1)
    CheckBox mActivityCBox1;
    @Bind(R.id.activity_cBox3)
    CheckBox mActivityCBox3;
    @Bind(R.id.wy_bt_qbsb)
    Button mWyBtQbsb;
    @Bind(R.id.rl_text_title)
    TextView mRlTextTitle;

    private int type = 0;
    private String title = null, neirong = null, id, isController = null, isLead = null;

    private String filename = "data.png";
    private File file1, file2, file3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intelligence, false);
        ButterKnife.bind(this);
        id = UserSessionManager.getInstance().getUserId();

    }

    @OnClick({R.id.back, R.id.iv01, R.id.iv02, R.id.iv03, R.id.wy_bt_qbsb})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.iv01:
                type = 1;
                showDialog(this);
                break;
            case R.id.iv02:
                type = 2;
                showDialog(this);
                break;
            case R.id.iv03:
                type = 3;
                showDialog(this);
                break;
            case R.id.wy_bt_qbsb:

                title = mActivityEdit.getText().toString();
                if (title != null) {

                    neirong = mActivityParticularsEdit.getText().toString();
                    if (neirong != null) {

                        if (mActivityCBox1.isChecked()) {
                            isController = "0001";
                        } else {
                            isController = "0002";
                        }
                        if (mActivityCBox3.isChecked()) {
                            isLead = "0001";
                        } else {
                            isLead = "0002";
                        }
                        if (isController.equals("0002")
                                && isLead.equals("0002")) {
                            ToastMaker.showToastShort(R.string.choose_reporter_first);
                        } else {
                            if (file1 != null) {
                                requestData(YXHttpUrl.WY_INTELLIGENCE_UP, title,
                                        "0002", neirong, id, isController, isLead);
                            } else {
                                requestDataNoImage(YXHttpUrl.WY_INTELLIGENCE_UPNO, title,
                                        "0002", neirong, id, isController, isLead);
                            }
                        }

                    } else {
                        ToastMaker.showToastShort(R.string.report_detail_empty);
                    }
                } else {
                    ToastMaker.showToastShort(R.string.report_title_empty);
                }

                break;
            default:
                break;

        }
    }

    public Dialog showDialog(final Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.alert_dialogmenu, null);

        final Dialog dialog = new AlertDialog.Builder(context).setView(view).create();

        dialog.show();
        Button take = (Button) view.findViewById(R.id.btn_take_photo);
        Button pick = (Button) view.findViewById(R.id.btn_pick_photo);
        final Button cancel = (Button) view.findViewById(R.id.btn_cancel);
        take.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 2);
                    Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    startActivityForResult(intent2, 2);
                } else {
                    Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    startActivityForResult(intent2, 2);
                }
                dialog.dismiss();

            }
        });
        pick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                //intent = new Intent(Intent.ACTION_GET_CONTENT);
                /* 开启Pictures画面Type设定为image */
                intent.setType("image/*");
                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                intent.setAction(Intent.ACTION_GET_CONTENT);
                /* 取得相片后返回本画面 */
                startActivityForResult(intent, 1);
                dialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        return dialog;
    }

    private final String PNG_FILE_NAME = "intelligence.png";

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Bitmap bitmap = null;
        if (data != null) {
            try {
                if (requestCode == 1) {
                    Uri selectedImage = data.getData();

                    if (ObjUtil.isEmpty(selectedImage) || TextUtils.isEmpty(selectedImage.toString())){
                        ToastMaker.showToastShort(R.string.not_choose_picture);
                    }
                    bitmap = BitmapFactory.decodeStream(this
                            .getContentResolver().openInputStream(Uri.parse(selectedImage.toString())));
                }
                if (requestCode == 2) {
                    if (data.getExtras() != null) {
                        Bundle bundle = data.getExtras();
                        bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
                    } else {
                        ToastMaker.showToastShort(R.string.not_take_picture);
                    }
                }

                if (ObjUtil.isEmpty(bitmap)){
                    ToastMaker.showToastShort(R.string.not_choose_picture);
                }

                viewKJ(bitmap);
                saveImageToFile(bitmap);
            }catch (Exception e){
                e.printStackTrace();
            }
        } else {
            ToastMaker.showToastShort(R.string.not_choose_picture);
        }
    }

    private void saveImageToFile(Bitmap bitmap) {
        try {
            String filePath = null;
            String fileName = FileUtil.getLocalFileImagePath() + PNG_FILE_NAME + type;
            if ((filePath = BitmapUtil.compressImage(this, bitmap, fileName, 20)) == null) {
                ToastMaker.showToastShort(R.string.select_photo_error);
                return;
            }

            switch (type) {
                case 1:
                    file1 = new File(filePath);
                    break;
                case 2:
                    file2 = new File(filePath);
                    break;
                case 3:
                    file3 = new File(filePath);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void viewKJ(Bitmap bitmap) {
        switch (type) {
            case 1:
                mIv01.setImageBitmap(bitmap);
                mIv02.setVisibility(View.VISIBLE);
                break;

            case 2:
                mIv02.setImageBitmap(bitmap);
                mIv03.setVisibility(View.VISIBLE);
                break;
            case 3:
                mIv03.setImageBitmap(bitmap);
                break;
        }
    }

    private void requestDataNoImage(String url, String reportName, String reportType, String reportDetail, String reportId, String isController, String isLead) {
        OkHttpUtils.post().
                url(url)
                .addParams("reportName", reportName)
                .addParams("reportType", reportType)
                .addParams("reportDetail", reportDetail)
                .addParams("reportId", reportId)
                .addParams("isController", isController)
                .addParams("isLead", isLead)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMaker.showToastShort(R.string.generic_error);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (response != null) {
                            ToastMaker.showToastShort(R.string.upload_success);
                            finish();
                        }
                    }
                });

    }

    private void requestData(String url, String reportName, String reportType, String reportDetail, String reportId, String isController, String isLead) {
        PostFormBuilder url1 = OkHttpUtils.post().url(url);
        PostFormBuilder postFormBuilder = null;
        if (file1 != null && file2 != null && file3 != null) {
            postFormBuilder = url1.addFile("files", filename, file1)
                    .addFile("files", filename, file2)
                    .addFile("files", filename, file3);

        } else if (file1 != null && file2 != null) {
            postFormBuilder = url1.addFile("files", filename, file1)
                    .addFile("files", filename, file2);
        } else if (file1 != null) {
            postFormBuilder = url1.addFile("files", filename, file1);
        }


        postFormBuilder.addParams("reportName", reportName)
                .addParams("reportType", reportType)
                .addParams("reportDetail", reportDetail)
                .addParams("reportId", reportId)
                .addParams("isController", isController)
                .addParams("isLead", isLead)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMaker.showToastShort(R.string.generic_error);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (response != null) {
                            ToastMaker.showToastShort(R.string.upload_success);
                            finish();
                        }

                    }
                });

    }

    @Override
    protected void onStart() {
        super.onStart();
        mRlTextTitle.setText(getResources().getString(R.string.intelligency_report));
    }
}
